{% extends "base.html" %}

{% block title %}预约统计分析{% endblock %}

{% block extra_css %}
<style>
    .stats-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 2rem 0;
        border-radius: 0 0 1rem 1rem;
        margin-bottom: 2rem;
    }

    .filter-card {
        background: white;
        border-radius: 0.75rem;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        padding: 1.5rem;
        margin-bottom: 2rem;
    }

    .filter-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 1rem;
    }

    .overview-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .stat-card {
        background: white;
        border-radius: 1rem;
        padding: 2rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        text-align: center;
        position: relative;
        overflow: hidden;
        transition: transform 0.3s ease;
    }

    .stat-card:hover {
        transform: translateY(-5px);
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: var(--gradient);
    }

    .stat-card.primary {
        --gradient: linear-gradient(135deg, #667eea, #764ba2);
    }

    .stat-card.success {
        --gradient: linear-gradient(135deg, #28a745, #20c997);
    }

    .stat-card.warning {
        --gradient: linear-gradient(135deg, #ffc107, #fd7e14);
    }

    .stat-card.info {
        --gradient: linear-gradient(135deg, #17a2b8, #138496);
    }

    .stat-card.danger {
        --gradient: linear-gradient(135deg, #dc3545, #c82333);
    }

    .stat-icon {
        width: 80px;
        height: 80px;
        background: var(--gradient);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2rem;
        margin: 0 auto 1rem;
    }

    .stat-number {
        font-size: 2.5rem;
        font-weight: bold;
        color: #2c3e50;
        margin-bottom: 0.5rem;
    }

    .stat-label {
        color: #6c757d;
        font-size: 1rem;
        margin-bottom: 0.5rem;
    }

    .stat-change {
        font-size: 0.875rem;
        font-weight: 500;
    }

    .stat-change.positive {
        color: #28a745;
    }

    .stat-change.negative {
        color: #dc3545;
    }

    .chart-card {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        margin-bottom: 2rem;
    }

    .chart-header {
        padding: 1.5rem;
        border-bottom: 1px solid #e9ecef;
        background: #f8f9fa;
        border-radius: 1rem 1rem 0 0;
    }

    .chart-body {
        padding: 1.5rem;
    }

    .chart-container {
        position: relative;
        height: 400px;
        margin-bottom: 1rem;
    }

    .chart-container.small {
        height: 300px;
    }

    .table-card {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        margin-bottom: 2rem;
    }

    .table-header {
        background: #f8f9fa;
        padding: 1.5rem;
        border-bottom: 1px solid #e9ecef;
    }

    .ranking-item {
        display: flex;
        align-items: center;
        padding: 1rem;
        border-bottom: 1px solid #f8f9fa;
        transition: background-color 0.3s ease;
    }

    .ranking-item:hover {
        background: #f8f9fa;
    }

    .ranking-item:last-child {
        border-bottom: none;
    }

    .ranking-number {
        width: 40px;
        height: 40px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        margin-right: 1rem;
        flex-shrink: 0;
    }

    .ranking-number.top-3 {
        background: linear-gradient(135deg, #ffd700, #ffed4e);
        color: #333;
    }

    .ranking-info {
        flex: 1;
    }

    .ranking-name {
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 0.25rem;
    }

    .ranking-meta {
        font-size: 0.875rem;
        color: #6c757d;
    }

    .ranking-value {
        font-weight: bold;
        color: #2c3e50;
        text-align: right;
    }

    .trend-indicator {
        display: inline-flex;
        align-items: center;
        font-size: 0.875rem;
        margin-left: 0.5rem;
    }

    .trend-up {
        color: #28a745;
    }

    .trend-down {
        color: #dc3545;
    }

    .pie-chart-legend {
        display: flex;
        flex-wrap: wrap;
        gap: 1rem;
        justify-content: center;
        margin-top: 1rem;
    }

    .legend-item {
        display: flex;
        align-items: center;
        font-size: 0.875rem;
    }

    .legend-color {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        margin-right: 0.5rem;
    }

    .period-tabs {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 0.5rem;
        padding: 0.25rem;
        display: inline-flex;
        margin-bottom: 1rem;
    }

    .period-tab {
        border: none;
        background: transparent;
        color: rgba(255, 255, 255, 0.8);
        padding: 0.5rem 1rem;
        border-radius: 0.375rem;
        transition: all 0.3s ease;
    }

    .period-tab.active {
        background: rgba(255, 255, 255, 0.2);
        color: white;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    }

    @media (max-width: 768px) {
        .stats-header {
            padding: 1rem 0;
        }

        .overview-grid {
            grid-template-columns: 1fr;
            gap: 1rem;
        }

        .filter-grid {
            grid-template-columns: 1fr;
        }

        .stat-number {
            font-size: 2rem;
        }

        .chart-container {
            height: 300px;
        }

        .chart-container.small {
            height: 250px;
        }

        .pie-chart-legend {
            flex-direction: column;
            align-items: flex-start;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="stats-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1 class="mb-0">
                    <i class="fas fa-chart-bar me-2"></i>预约统计分析
                </h1>
                <p class="mb-0 mt-2 opacity-75">深度洞察预约数据，优化运营决策</p>
            </div>
            <div class="col-md-4 text-end">
                <div class="period-tabs">
                    <button type="button" class="period-tab {% if current_period == 'week' %}active{% endif %}"
                            onclick="changePeriod('week')">周</button>
                    <button type="button" class="period-tab {% if current_period == 'month' %}active{% endif %}"
                            onclick="changePeriod('month')">月</button>
                    <button type="button" class="period-tab {% if current_period == 'quarter' %}active{% endif %}"
                            onclick="changePeriod('quarter')">季</button>
                    <button type="button" class="period-tab {% if current_period == 'year' %}active{% endif %}"
                            onclick="changePeriod('year')">年</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid">
    <!-- 筛选器 -->
    <div class="filter-card">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0">筛选条件</h5>
            <button type="button" class="btn btn-outline-primary" onclick="refreshData()">
                <i class="fas fa-sync-alt me-1"></i>刷新数据
            </button>
        </div>

        <form method="GET" action="{{ url_for('admin_reservations.statistics') }}" id="filterForm">
            <input type="hidden" name="period" value="{{ current_period }}">
            <div class="filter-grid">
                <div>
                    <label class="form-label">校区</label>
                    <select class="form-select" name="campus_id">
                        <option value="">所有校区</option>
                        {% for campus in campuses %}
                        <option value="{{ campus.id }}" {% if current_campus_id == campus.id %}selected{% endif %}>
                            {{ campus.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <div>
                    <label class="form-label">开始日期</label>
                    <input type="date" class="form-control" name="start_date" value="{{ start_date }}">
                </div>

                <div>
                    <label class="form-label">结束日期</label>
                    <input type="date" class="form-control" name="end_date" value="{{ end_date }}">
                </div>

                <div class="d-flex align-items-end">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search me-1"></i>应用筛选
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 总体统计 -->
    <div class="overview-grid">
        <div class="stat-card primary">
            <div class="stat-icon">
                <i class="fas fa-calendar-alt"></i>
            </div>
            <div class="stat-number">{{ overall_stats.total_reservations }}</div>
            <div class="stat-label">总预约数</div>
            <div class="stat-change positive">
                <i class="fas fa-arrow-up me-1"></i>+12% 环比上期
            </div>
        </div>

        <div class="stat-card success">
            <div class="stat-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-number">{{ overall_stats.completed_count }}</div>
            <div class="stat-label">已完成</div>
            <div class="stat-change positive">
                <i class="fas fa-arrow-up me-1"></i>+8% 环比上期
            </div>
        </div>

        <div class="stat-card warning">
            <div class="stat-icon">
                <i class="fas fa-hourglass-half"></i>
            </div>
            <div class="stat-number">{{ overall_stats.pending_count }}</div>
            <div class="stat-label">待处理</div>
            <div class="stat-change negative">
                <i class="fas fa-arrow-down me-1"></i>-5% 环比上期
            </div>
        </div>

        <div class="stat-card info">
            <div class="stat-icon">
                <i class="fas fa-money-bill-wave"></i>
            </div>
            <div class="stat-number">¥{{ overall_stats.total_revenue|round(0)|int }}</div>
            <div class="stat-label">总收入</div>
            <div class="stat-change positive">
                <i class="fas fa-arrow-up me-1"></i>+15% 环比上期
            </div>
        </div>

        <div class="stat-card danger">
            <div class="stat-icon">
                <i class="fas fa-ban"></i>
            </div>
            <div class="stat-number">{{ overall_stats.cancelled_count }}</div>
            <div class="stat-label">已取消</div>
            <div class="stat-change negative">
                <i class="fas fa-arrow-down me-1"></i>-3% 环比上期
            </div>
        </div>

        <div class="stat-card primary">
            <div class="stat-icon">
                <i class="fas fa-percentage"></i>
            </div>
            <div class="stat-number">{{ ((overall_stats.completed_count / overall_stats.total_reservations * 100) if overall_stats.total_reservations > 0 else 0)|round(1) }}%</div>
            <div class="stat-label">完成率</div>
            <div class="stat-change positive">
                <i class="fas fa-arrow-up me-1"></i>+2% 环比上期
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 预约趋势图 -->
        <div class="col-lg-8">
            <div class="chart-card">
                <div class="chart-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">预约趋势分析</h5>
                        <div class="btn-group btn-group-sm">
                            <button type="button" class="btn btn-outline-primary active" data-chart="line">
                                <i class="fas fa-chart-line me-1"></i>折线图
                            </button>
                            <button type="button" class="btn btn-outline-primary" data-chart="bar">
                                <i class="fas fa-chart-bar me-1"></i>柱状图
                            </button>
                        </div>
                    </div>
                </div>
                <div class="chart-body">
                    <div class="chart-container">
                        <canvas id="trendChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 状态分布饼图 -->
        <div class="col-lg-4">
            <div class="chart-card">
                <div class="chart-header">
                    <h5 class="mb-0">状态分布</h5>
                </div>
                <div class="chart-body">
                    <div class="chart-container small">
                        <canvas id="statusChart"></canvas>
                    </div>
                    <div class="pie-chart-legend">
                        <div class="legend-item">
                            <div class="legend-color" style="background: #28a745;"></div>
                            <span>已完成 ({{ status_distribution.completed or 0 }})</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #17a2b8;"></div>
                            <span>已确认 ({{ status_distribution.confirmed or 0 }})</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #ffc107;"></div>
                            <span>待处理 ({{ status_distribution.pending or 0 }})</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #dc3545;"></div>
                            <span>已取消 ({{ status_distribution.cancelled or 0 }})</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 教练工作量排行 -->
        <div class="col-lg-6">
            <div class="table-card">
                <div class="table-header">
                    <h5 class="mb-0">
                        <i class="fas fa-chalkboard-teacher me-2"></i>教练工作量排行
                    </h5>
                </div>
                <div>
                    {% for coach in coach_stats[:10] %}
                    <div class="ranking-item">
                        <div class="ranking-number {% if loop.index <= 3 %}top-3{% endif %}">
                            {{ loop.index }}
                        </div>
                        <div class="ranking-info">
                            <div class="ranking-name">{{ coach.coach_name }}</div>
                            <div class="ranking-meta">{{ coach.total_hours|round(1) }} 小时课程</div>
                        </div>
                        <div class="ranking-value">
                            {{ coach.total_reservations }} 节课
                            <div class="trend-indicator trend-up">
                                <i class="fas fa-arrow-up me-1"></i>+5%
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- 收入分析 -->
        <div class="col-lg-6">
            <div class="chart-card">
                <div class="chart-header">
                    <h5 class="mb-0">收入分析</h5>
                </div>
                <div class="chart-body">
                    <div class="chart-container small">
                        <canvas id="revenueChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// 图表数据
const trendData = {{ trend_data|tojson }};
const statusData = {{ status_distribution|tojson }};
const revenueData = {{ revenue_stats|tojson }};

// 颜色配置
const colors = {
    primary: '#667eea',
    success: '#28a745',
    warning: '#ffc107',
    danger: '#dc3545',
    info: '#17a2b8'
};

// 初始化图表
let trendChart, statusChart, revenueChart;

$(document).ready(function() {
    initTrendChart();
    initStatusChart();
    initRevenueChart();

    // 图表类型切换
    $('[data-chart]').click(function() {
        const chartType = $(this).data('chart');
        $('[data-chart]').removeClass('active');
        $(this).addClass('active');

        // 重新创建趋势图
        if (trendChart) {
            trendChart.destroy();
        }
        initTrendChart(chartType);
    });
});

// 初始化趋势图
function initTrendChart(type = 'line') {
    const ctx = document.getElementById('trendChart').getContext('2d');

    trendChart = new Chart(ctx, {
        type: type,
        data: {
            labels: trendData.labels || [],
            datasets: [
                {
                    label: '总预约',
                    data: trendData.data || [],
                    borderColor: colors.primary,
                    backgroundColor: type === 'bar' ? colors.primary + '20' : colors.primary + '10',
                    borderWidth: 2,
                    fill: type === 'line'
                },
                {
                    label: '已完成',
                    data: (trendData.completed || []),
                    borderColor: colors.success,
                    backgroundColor: type === 'bar' ? colors.success + '20' : colors.success + '10',
                    borderWidth: 2,
                    fill: type === 'line'
                },
                {
                    label: '已取消',
                    data: (trendData.cancelled || []),
                    borderColor: colors.danger,
                    backgroundColor: type === 'bar' ? colors.danger + '20' : colors.danger + '10',
                    borderWidth: 2,
                    fill: type === 'line'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: '#f8f9fa'
                    }
                },
                x: {
                    grid: {
                        color: '#f8f9fa'
                    }
                }
            }
        }
    });
}

// 初始化状态分布图
function initStatusChart() {
    const ctx = document.getElementById('statusChart').getContext('2d');

    const data = [
        statusData.completed || 0,
        statusData.confirmed || 0,
        statusData.pending || 0,
        statusData.cancelled || 0
    ];

    statusChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['已完成', '已确认', '待处理', '已取消'],
            datasets: [{
                data: data,
                backgroundColor: [
                    colors.success,
                    colors.info,
                    colors.warning,
                    colors.danger
                ],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
}

// 初始化收入图
function initRevenueChart() {
    const ctx = document.getElementById('revenueChart').getContext('2d');

    revenueChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['本周', '上周', '本月', '上月'],
            datasets: [{
                label: '收入（元）',
                data: [8500, 7200, 32000, 28000],
                backgroundColor: [
                    colors.primary + '80',
                    colors.info + '80',
                    colors.success + '80',
                    colors.warning + '80'
                ],
                borderColor: [
                    colors.primary,
                    colors.info,
                    colors.success,
                    colors.warning
                ],
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: '#f8f9fa'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
}

// 切换时间周期
function changePeriod(period) {
    const url = new URL(window.location);
    url.searchParams.set('period', period);
    window.location.href = url.toString();
}

// 刷新数据
function refreshData() {
    location.reload();
}


// 显示提示信息
function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' :
                      type === 'info' ? 'alert-info' : 'alert-danger';
    const icon = type === 'success' ? 'check-circle' :
                 type === 'info' ? 'info-circle' : 'exclamation-triangle';

    const alert = $(`
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 9999;">
            <i class="fas fa-${icon} me-2"></i>${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `);

    $('body').append(alert);

    setTimeout(function() {
        alert.alert('close');
    }, 3000);
}
</script>
{% endblock %}